using System.Collections;
using System.Collections.Generic;
using System.Linq;
using MyTanks;
using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Rendering;
using Unity.Transforms;
using UnityEngine;

namespace MyTanks
{
    public partial struct TankAttackSystem : ISystem
    {
        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<Turret>();
        }

        private int currentRound;

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            // var spin = quaternion.RotateY(SystemAPI.Time.DeltaTime * math.PI);
            // foreach (var transform in
            //          SystemAPI.Query<RefRW<LocalTransform>>()
            //              .WithAll<Turret>())
            // {
            //     // transform.ValueRW.Rotation = math.mul(spin, transform.ValueRO.Rotation);
            // }

            var config = SystemAPI.GetSingleton<MyTanksConfig>();
            var shellsHolder = SystemAPI.GetSingletonEntity<ShellHolder>();
            var shellBuffer = SystemAPI.GetBuffer<ShellBufferComponent>(shellsHolder);

            var shootRound = (int)(SystemAPI.Time.ElapsedTime / config.shootInterval);
            if (currentRound != shootRound)
            {
                currentRound = shootRound;
                foreach (var (turret, localToWorld) in
                         SystemAPI.Query<RefRO<Turret>, RefRO<LocalToWorld>>()
                             .WithAll<Turret>())
                {
                    var spawnPoint = SystemAPI.GetComponent<LocalToWorld>(turret.ValueRO.shellSpawnPoint);


                    for (int i = 0; i < shellBuffer.Length; i++)
                    {
                        var shellData = shellBuffer[i];
                        if (SystemAPI.IsComponentEnabled<ShellIsIdle>(shellData.shell))
                        {
                            var shellComponent = SystemAPI.GetComponentRW<Shell>(shellData.shell);
                            var shellTransform = SystemAPI.GetComponentRW<LocalTransform>(shellData.shell);
                            shellComponent.ValueRW.velocity = spawnPoint.Up * config.shellFlySpeed;
                            shellComponent.ValueRW.duration = 0f;
                            shellTransform.ValueRW.Position = spawnPoint.Position;
                            shellTransform.ValueRW.Rotation =
                                quaternion.LookRotation(spawnPoint.Up, new float3(0, 1, 0));
                            shellTransform.ValueRW.Scale =
                                SystemAPI.GetComponent<LocalTransform>(config.shellPrefab).Scale;
                            state.EntityManager.SetComponentEnabled<ShellIsIdle>(shellData.shell, false);
                            break;
                        }
                    }
                }
            }
        }
    }
}